package com.smarttest.net

import android.content.Context
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.error
import org.reactivestreams.Subscriber
import org.reactivestreams.Subscription

//Subscriber
class NetProgressFlowable<T : Any?>(context: Context, dialogMessage: String, private val dataCallBack: (Int, T) -> Unit, cancelable: Boolean = true) : Subscriber<T>, AnkoLogger {
    private var s: Subscription? = null
    private val progressDialogHandler = NetProgressHandler(context, dialogMessage, cancelable) {
        dataCallBack(FAILED, false as T)
        s?.cancel()
    }

    override fun onComplete() {
        s?.cancel()
        dismissProgressDialog()
        error { "onComplete" }
    }

    override fun onSubscribe(s: Subscription?) {
        this.s = s
        s?.request(Long.MAX_VALUE)
        showProgressDialog()
        error { "onSubscribe" }
    }

    override fun onNext(t: T) {
        error { "onNext" }
        dataCallBack(SUCCESS, t)//由于在complete调用所以不需要调用清除dialog
        onComplete()
    }

    override fun onError(t: Throwable?) {
        error { "onError:::::${t?.message}" }
        dismissProgressDialog()
        s?.cancel()
    }


    private fun showProgressDialog() {
        error { "showProgressDialog" }
        progressDialogHandler.obtainMessage(NetProgressHandler.SHOW_PROGRESS_DIALOG).sendToTarget()
    }

    private fun dismissProgressDialog() {
        error { "dismissProgressDialog" }
        progressDialogHandler.obtainMessage(NetProgressHandler.DISMISS_PROGRESS_DIALOG).sendToTarget()
    }

    companion object {
        const val FAILED = 0
        const val SUCCESS = 1
    }
}